package com.zzw.bridge.security.access;

import com.zzw.bridge.security.filter.BodyReaderHttpServletRequestWrapper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Security请求拦截（feign调用在请求头加入key：x-from，value:feign）
 *
 * @author XiaoJie
 * @date 2025/5/15 14:07
 */
@Service
@AllArgsConstructor
public class InServiceAccessImpl implements InServiceAccess {
	private final HttpServletRequest request;

	/**
	 * 此方法不能拦截内部调用，会拦截调所用的请求
	 *
	 * @return
	 */
	@Override
	public Boolean isService () {
		ServletRequest requestWrapper = null;
		if (request != null) {
			try {
				requestWrapper = new BodyReaderHttpServletRequestWrapper(request);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		HttpServletRequest requestWrapper1 = (HttpServletRequest) requestWrapper;
//		String path = request.getRequestURI();
//		String url="/business/file/getDownload/**";
//		AntPathMatcher pathMatcher = new AntPathMatcher();
//		boolean match = pathMatcher.match(url, path);
		// //获取请求头
		String header = requestWrapper1.getHeader("x-from");
		String accessToken = requestWrapper1.getHeader("Authorization");
		if (StringUtils.isBlank(accessToken)) {
			accessToken = requestWrapper1.getParameter("access_token");
		}
		if (StringUtils.isNotEmpty(accessToken) || (StringUtils.isNotEmpty(header) && "feign".equals(header))) {
			return true;
		}
		return false;
	}
}
